package com.zhiqianbao.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.Toast;

import com.zhiqianbao.R;
import com.zhiqianbao.shared.SharedPreferanceUtils;
import com.zhiqianbao.utils.Constants;
import com.zhiqianbao.utils.FileUtils;
import com.zhiqianbao.view.WebView4Scroll;

import java.util.ArrayList;
import java.util.List;
import cn.trinea.android.common.util.StringUtils;

import static com.zhiqianbao.R.id.button_ruturn;

/**
 * Created by 子龙 on 2017/8/7.
 * 最新公告
 */

public class LatestAnmentActivity extends BaseActivity {
    WebView4Scroll applyStudentRateWebview;
    SwipeRefreshLayout swipRefresh;

    private boolean isLoading=false;//第一次加载状态
    private  Button returnButton;
    private  SharedPreferanceUtils sharedPreferanceUtils;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_active_apply_tab);
        initView();
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void onPause() {
        super.onPause();
        sendRefreshReceiver();
    }

    /**
     * 通知主页面刷新消息提醒
     */
    public void sendRefreshReceiver(){
        Intent intent=new Intent();
        intent.setAction(MainActivity.REFRESH_MSGS);
        sendBroadcast(intent);
    }
    private void initView() {
         applyStudentRateWebview=(WebView4Scroll)findViewById(R.id.apply_student_rate_webview);
         swipRefresh=(SwipeRefreshLayout)findViewById(R.id.swipRefresh);

        applyStudentRateWebview.setSwipeRefreshLayout(swipRefresh);
        WebSettings webSettings = applyStudentRateWebview.getSettings();
        //设置WebView属性，能够执行Javascript脚本
        webSettings.setJavaScriptEnabled(true);
        webSettings.setDefaultFontSize(16); //支持通过JS打开新窗口
        webSettings.setUseWideViewPort(true);
        webSettings.setLoadWithOverviewMode(true);
        //设置可以访问文件
        webSettings.setAllowFileAccess(true);
        //设置支持缩放
        webSettings.setBuiltInZoomControls(false);
        //加载需要显示的网页
        applyStudentRateWebview.loadUrl(Constants.WEB_ROOT + "/webview/list");
        //通过js与本地接口交互
        applyStudentRateWebview.addJavascriptInterface(this, "applyActive");

        applyStudentRateWebview.setWebViewClient(new WebViewClient() {
              @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return true;
            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);

            }

            @Override
            public void onPageFinished(WebView view, String url) {
                try{
                    swipRefresh.setRefreshing(false);
                }catch (Exception e){

                }

            }
        });

        applyStudentRateWebview.setWebChromeClient(new WebChromeClient(){
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                // TODO 自动生成的方法存根
                try{
                    if (!TextUtils.isEmpty(String.valueOf(newProgress))){
                        if(newProgress==100){
                            if(!isLoading) {
                                isLoading=true;
                                swipRefresh.setRefreshing(false);
                            }
                        }else{

                            if(!swipRefresh.isRefreshing()){
                                swipRefresh.setRefreshing(true);
                            }
                        }
                    }

                }catch (Exception e){

                }

                super.onProgressChanged(view, newProgress);
            }
        });

         returnButton = (Button) findViewById(button_ruturn);
        if (null != returnButton) {
            returnButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if(applyStudentRateWebview.canGoBack()) {//当webview不是处于第一页面时，返回上一个页面
                        applyStudentRateWebview.goBack();
                    }
                    else {//当webview处于第一页面时,直接退出程序
                        finish();
                    }
                }
            });
        }

        swipRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                //查询借款进度接口
                applyStudentRateWebview.reload();
            }
        });
    }

    //设置返回键动作（防止按返回键直接退出程序)
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // TODO 自动生成的方法存根
        if(keyCode==KeyEvent.KEYCODE_BACK) {
            if(applyStudentRateWebview.canGoBack()) {//当webview不是处于第一页面时，返回上一个页面
                applyStudentRateWebview.goBack();
                sharedPreferanceUtils = new SharedPreferanceUtils(this);
                sharedPreferanceUtils.setBoolean(true);
                return true;
            }
            else {//当webview处于第一页面时,直接退出程序
                sharedPreferanceUtils = new SharedPreferanceUtils(this);
                sharedPreferanceUtils.setBoolean(true);
                finish();
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * ids是如果公告有新更新公告的id总和
     * @param ids
     */
    @JavascriptInterface
    public void saveAllIds(String ids) {
        Message message = new Message();
        try {
            String idsText = FileUtils.getStrByFilename("ids.txt");

            String allIds = "";
            String clickedIds = "";

            if (!StringUtils.isBlank(idsText)) {
                String[] temp = idsText.split(":");
                if (temp.length == 1) {
                    allIds = idsText.split(":")[0];
                    clickedIds = "";
                } else {
                    allIds = idsText.split(":")[0];
                    clickedIds = idsText.split(":")[1];
                }
            }

            List<String> idsList = str2list(ids);
            List<String> allIdsList = str2list(allIds);
            List<String> clickedList = str2list(clickedIds);
            //看是否有新增的公告信息，放入allIds中
            List<String> addAllIdsList = getNoInList(idsList, allIdsList);
            //组成新的allIdsList
            if (!addAllIdsList.isEmpty()) {
                allIdsList.addAll(addAllIdsList);
            }

            //组成新的allIds
            allIds = getStrByList(allIdsList);
            //保存未读公告个数
            SharedPreferanceUtils sharedPreferanceUtils = new SharedPreferanceUtils(this);
            sharedPreferanceUtils.setNoannouncementCounts(allIdsList.size()-clickedList.size());
            //保存到本地文本
            FileUtils.saveToRom(LatestAnmentActivity.this, allIds, clickedIds, "ids.txt");

            message.what = LatestAnmentActivity.this.RESULT_OK;
            message.obj = clickedIds;
        } catch (Exception e) {
            e.printStackTrace();
            message.what = LatestAnmentActivity.this.RESULT_CANCELED;
        }
        if (!isFinishing()){
            showHandler.sendMessage(message);
        }

    }

    @JavascriptInterface
    public void saveClickId(String id) {
        try {
            String idsText = FileUtils.getStrByFilename("ids.txt");
            String allIds = "";
            String clickedIds = "";
            if (!StringUtils.isBlank(idsText)) {
                String[] temp = idsText.split(":");
                if (temp.length == 1) {
                    allIds = idsText.split(":")[0];
                    clickedIds = "";
                } else {
                    allIds = idsText.split(":")[0];
                    clickedIds = idsText.split(":")[1];
                }
            }
            List<String> clickedList = str2list(clickedIds);
            List<String> allIdsList=str2list(allIds);
            if (!clickedList.contains(id)) {
                clickedList.add(id);
            }
            clickedIds = getStrByList(clickedList);
            //保存未读公告个数
            SharedPreferanceUtils sharedPreferanceUtils = new SharedPreferanceUtils(this);
            sharedPreferanceUtils.setNoannouncementCounts(allIdsList.size()-clickedList.size());
            //保存到本地文本
            FileUtils.saveToRom(LatestAnmentActivity.this, allIds, clickedIds, "ids.txt");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 返回list1中的数据 不在 list2 的数据
     *
     * @param list1
     * @param list2
     * @return
     */
    public List<String> getNoInList(List<String> list1, List<String> list2) {
        List<String> result = new ArrayList<>();
        for (String id : list1) {
            if (!list2.contains(id)) {
                result.add(id);
            }
        }
        return result;
    }

    /**
     * @param ids
     * @return
     */
    public List<String> str2list(String ids) {
        List<String> list = new ArrayList<>();
        if (StringUtils.isBlank(ids)) {
            return list;
        }
        String[] idsArray = ids.split(",");
        for (String id : idsArray) {
            list.add(id);
        }
        return list;
    }

    /**
     * @param list
     * @return
     */
    public String getStrByList(List<String> list) {
        String st = "";
        for (String id : list) {
            st += id + ",";
        }
        if (st.indexOf(",") != -1) {
            st = st.substring(0, st.length() - 1);
        }
        return st;
    }

    private Handler showHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case -1:
                    String clickedIds = (String) msg.obj;
                    if(!TextUtils.isEmpty(clickedIds)){
                        applyStudentRateWebview.loadUrl("javascript:showClicked('" + clickedIds + "')");
                    }
                    //applyStudentRateWebview.loadUrl("javascript:showClicked('" + "1" + "')");
                    break;
                case 0:
                    try {
                        Toast.makeText(LatestAnmentActivity.this, "错误", Toast.LENGTH_LONG).show();
                    } catch (Exception e) {

                    }
                    break;
            }
        }
    };

}
